//
//  checkOutFinish_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 22-05-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "checkOutFinish_ViewController.h"
#import "dao.h"

@interface checkOutFinish_ViewController ()

@end

@implementation checkOutFinish_ViewController

@synthesize viewSendInvoice, objActivitySendInvoice, viewLoading;
@synthesize json;
@synthesize lblFechaDespachoDesde, lblFechaDespachoHasta, lblNroInvoice;

NSTimer *timerSendInvoice;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) loadTabbar{
    //-------------------------------------------------------------------------------------
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    NSArray *ArrayResumeShoppingCart;
    NSString *strTotalCarro = @"0";
    
    ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUsuario];
    
    if (ArrayResumeShoppingCart.count > 0) {
        
        NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
        NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
        
        strTotalCarro = ArrayResumeShoppingCart[1];
    }
    
    //----------------------------------
    UITabBar *tabBar = self.tabBarController.tabBar; //tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
    UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
    UITabBarItem *tabBarItem5 = [tabBar.items objectAtIndex:4];
    
    tabBarItem1.selectedImage = [[UIImage imageNamed:@"icon_inicio_activo.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.image = [[UIImage imageNamed:@"icon_inicio.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.title = @"Inicio";
    
    tabBarItem2.selectedImage = [[UIImage imageNamed:@"icon_buscar_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.image = [[UIImage imageNamed:@"icon_buscar.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.title = @"Buscar";
    
    tabBarItem3.selectedImage = [[UIImage imageNamed:@"icon_carro_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.image = [[UIImage imageNamed:@"icon_carro.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.title = @"Carro";
    tabBarItem3.badgeValue = strTotalCarro;
    
    tabBarItem4.selectedImage = [[UIImage imageNamed:@"icon_cuenta_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.image = [[UIImage imageNamed:@"icon_cuenta.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.title = @"Cuenta";
    
    tabBarItem5.selectedImage = [[UIImage imageNamed:@"icon_chat_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.image = [[UIImage imageNamed:@"icon_chat.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.title = @"Chat";
    //----------------------------------
}

-(bool) updateInvoicePayTransaction: (int) intIdResumenNotaVenta intIdTransaccionPago:(int) intIdTransaccionPago{

    dao *objDAO = [[dao alloc] init];

    int intIdUsuario = [objDAO obtainCurrentIdUser];
    int intIdTransaction = 0;
    
//  confirmaJsonTransaccionTransbank(CInt(strIdUsuario), CInt(strIdResumenNotaVenta), CInt(strIdTransaccionPago))
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraNotaVenta.aspx?strJsonBase=JsonConfirmaTransaccionTransbank&strIdUsuario=%i&strIdResumenNotaVenta=%i&strIdTransaccionPago=%i",
                        intIdUsuario, intIdResumenNotaVenta, intIdTransaccionPago];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        NSLog(@"Exito");
        
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        //****Id del cliente relacionado al usuario para grabar la sucursal por defecto con los datos de dirección
        intIdTransaction = [ [[json objectAtIndex:0] objectForKey:@"idTransaction"] intValue];

        if (intIdTransaction == 1) {

            return YES;
        }else{
        
            return NO;
        }
        
    }else{
        
        NSLog(@"Error");
        
        return NO;
    }
}

-(int) insertInvoiceCloud{

    int intIdUsuario = 0;
    int intIdResumenCarro = 0;
    int intIdInvoiceNumber = 0;
    int intIdDireccionCliente = 0; //Dirección por defecto
    
    dao *objDAO = [[dao alloc] init];
    
    intIdUsuario = [objDAO obtainCurrentIdUser];
    intIdResumenCarro = [objDAO obtainIdShoppingCart:intIdUsuario];
    
    NSArray *ArrayDireccion;
    
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    ArrayDireccion = [objDAO obtainDireccionCliente:intIdUsuario];
    
    if (ArrayDireccion.count > 0) {
        
        intIdDireccionCliente = [ArrayDireccion[7] intValue];
        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        NSString *strFechaDespacho = [prefs stringForKey:@"strFechaEntrega"];
        
        NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraNotaVenta.aspx?strJsonBase=JsonRegistraNotaVenta&strIdUsuario=%i&strIdTipoDocumentoSII=39&strIdSesionLogin=-1&strIdFormaPago=1&strIdEstadoEntrega=2&strIdResumenCarroCompra=%i&strIdDireccioneCliente=%i&strFechaDespacho=%@",
                            intIdUsuario, intIdResumenCarro, intIdDireccionCliente, strFechaDespacho];
        
        NSURL *url = [NSURL URLWithString:strUrl];
        
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
        
        NSURLResponse * response = nil;
        NSError * error = nil;
        NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                              returningResponse:&response
                                                          error:&error];
        if (error == nil)
        {
            NSLog(@"Exito");
            
            json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            
            //****Id del cliente relacionado al usuario para grabar la sucursal por defecto con los datos de dirección
            intIdInvoiceNumber = [ [[json objectAtIndex:0] objectForKey:@"nvid"] intValue];

            if (intIdInvoiceNumber > 0) {

                bool blnRetorno = [self updateInvoicePayTransaction:intIdInvoiceNumber intIdTransaccionPago:1];
 
                if (blnRetorno) {
                    
                    [prefs setObject:@"Sin especificar" forKey:@"strFechaEntrega"];   //Define la fecha de entrega a asignar en la orden cada vez que se va a realizar una transacción, se limpia al presionar "Pagar".
                    
                    [prefs setObject:@"" forKey:@"strFechaEntregaDescription"];       //Almacena la fecha en formato "2014/11/24 Miércoles"
                }
            }
            
            return intIdInvoiceNumber;
        }else{
            
            NSLog(@"Error");
            
            return 0;
        }

    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Error al obtener el identificador de direccion del cliente, intente nuevamente."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return 0;
    }
    
}

- (void) sendInvoiceSelector:(NSTimer *) timer {
    
    //Detenemos el timer
    [timerSendInvoice invalidate];
    timerSendInvoice = nil;
    
    /*
     1.- Lanzar un NSURL Session Task hacia el cloud sincrónico
     2.- Con respuesta grabar en sqlLite
     3.- Mandar mensaje de alerta
    */
   
    int intIdInvoiceNumber = [self insertInvoiceCloud];
    
    NSLog(@"intIdInvoiceNumber =%i", intIdInvoiceNumber);

    lblNroInvoice.text = [NSString stringWithFormat:@"%i", intIdInvoiceNumber];
    
    //Si todo lo anterior sucede bien ocultar la vista
    viewSendInvoice.hidden = YES;
    
    viewLoading.hidden = YES;
    
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    //**************************************
    //Delete Shopping Cart
    [objDAO deleteProductsShoppingCart:intIdUsuario];

    //**************************************
    
   [objDAO deleteLoading];
    
   [self loadTabbar];
}

- (void)viewWillAppear:(BOOL)animated {
    
    dao *objDAO = [[dao alloc] init];
    
    if ([objDAO obtainLoading] == 1) {

        viewSendInvoice.hidden = NO;
        
        timerSendInvoice = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(sendInvoiceSelector:) userInfo:nil repeats:YES];

    }else{
        //Error
        [self.tabBarController setSelectedIndex:0];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    // saving an NSString
    [prefs setObject:lblNroInvoice.text forKey:@"strNroInvoiceSelected"];
    
    return YES;
}


@end






